package com.cqd.rp_goods.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.cqd.rp_goods.dto.ResultEntity;
import com.cqd.rp_goods.dto.pay.PayConfig;
import com.cqd.rp_goods.service.EcPayService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Slf4j
@CrossOrigin
public class EcPayController {
    @Autowired
    EcPayService ecPayService;

    @Autowired
    PayConfig payConfig;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/createQrCodePay")
    public ResultEntity createQrCodePay(String orderNo) throws AlipayApiException {
        log.info("创建支付宝扫码订单开始编号为：{}", orderNo);
        if(redisTemplate.hasKey(orderNo)){
            String qrcode = redisTemplate.opsForValue().get(orderNo);
            log.info("根据orderNo:{}到redis 中查询二维码:{}",orderNo,qrcode);
            return ResultEntity.ok("创建支付宝扫码支付订单成功",qrcode);
        }
        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",orderNo); //商户订单号，需要保证不重复
        map.put("trade_no",orderNo);
        map.put("total_amount","0.01"); //订单金额
        map.put("subject","Iphone6 16G");   //订单标题
        map.put("store_id","2016101800717939");   //商户门店编号
        map.put("timeout_express","7200m"); //交易超时时间
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(payConfig.getCallBackUrl());


        AlipayTradePrecreateResponse qrCodePay = ecPayService.createQrCodePay(map);
        String qrcode = ecPayService.getEcPayQRCode(qrCodePay);
        log.info("创建支付宝扫码订单结束订单号为:{}",orderNo);
        return ResultEntity.ok("创建支付宝扫码支付订单成功",qrcode);
    }
}
